package com.me.mysqladmin.dao.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.sql.RowSet;

import org.springframework.stereotype.Repository;

import com.me.mysqladmin.dao.DatabaseDAO;
import com.me.mysqladmin.entity.DataBase;
import com.me.mysqladmin.util.JDBCUtil;
import com.me.mysqladmin.util.RowSetUtil;

@Repository("databaseDAO")
public class DatabaseDAOImpl extends BaseDAOImpl<DataBase> implements DatabaseDAO {
	// 集中定义SQL语句
	private static String CREATE = "CREATE DATABASE ";
	private static String DROP = "DROP DATABASE ";
	private static String QUERY_ALL = "SELECT * FROM INFORMATION_SCHEMA.SCHEMATA";
	private static String QUERY_ALL_NAMES = "SHOW DATABASES";
	
	/**
	 * 创建数据库
	 */
	@Override
	public Integer create(String dbName) throws SQLException {
		return baseDML(CREATE + dbName);
	}

	/**
	 * 删除数据库
	 */
	@Override
	public Integer drop(String dbName) throws SQLException {
		return baseDML(DROP + dbName);
	}
	
	/**
	 * 查询所有数据库
	 */
	@Override
	public List<DataBase> queryAll() {
		try {
			return query(QUERY_ALL);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return Collections.emptyList();
	}
	
	/**
	 * 查询所有数据库
	 */
	@Override
	public List<Map<String, Object>> queryAllMap() {
		try {
			return queryMap(QUERY_ALL);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return Collections.emptyList();
	}
	
	/**
	 * 查询所有数据库名称
	 */
	@Override
	public List<String> queryNames() {
		List<String> dbNames = new ArrayList<>();
		try {
			List<Map<Integer,Object>> listMap = querySpecificCols(QUERY_ALL_NAMES, 1);
			for(Map<Integer,Object> map : listMap){
				dbNames.add(map.get(1).toString());
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return dbNames;
	}

	/**
	 * 判断连接状态
	 */
	@Override
	public boolean isActive() {
		boolean flag = false;
		Connection conn = null;
		try {
			conn = dataSource.getConnection();
			if(conn != null){
				flag = true;
			}
			return flag;
		} catch (Exception e) {
			return flag;
		} finally{
			JDBCUtil.closeConnection(conn);
		}
	}
	
	@Override
	protected List<DataBase> toEntities(RowSet rs) {
		return RowSetUtil.toEntiyList(rs, DataBase.class);
	}
}
